package com.keyancompany.zhongbaopingtai.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.activity.CirlcleDetailActivity;
import com.keyancompany.zhongbaopingtai.activity.TeamDetailActivity;
import com.keyancompany.zhongbaopingtai.adapter.MyTeamAdapter;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.EventBusEntity;
import com.keyancompany.zhongbaopingtai.model.TeamUser;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.IListView;
import com.keyancompany.zhongbaopingtai.weight.ISwipeRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.OnItemClick;

/**
 * 参与的团队 or 我的团队
 * <p>
 * Created by firefox on 2016/6/18.
 */
public class MyTeamFragment extends BaseFragment implements IAsyncHttpResponseHandler, SwipeRefreshLayout.OnRefreshListener {
    private static final String TUPE = "type";
    @Bind(R.id.listView)
    IListView listView;
    @Bind(R.id.swipe_layout)
    ISwipeRefreshLayout swipeLayout;
    MyTeamAdapter tca;
    private int type;
    private String res;
    private int currentPage = 1, total = 1;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public MyTeamFragment() {
    }

    /**
     * @param type 1 linshi
     * @return
     */
    public static MyTeamFragment newInstance(int type) {
        MyTeamFragment fragment = new MyTeamFragment();
        Bundle args = new Bundle();
        args.putInt(TUPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_team_circle;
    }

    @Override
    public void setUpViews() {
        EventBus.getDefault().register(this);
        initSwipeLayout(swipeLayout);
        type = getArguments().getInt(TUPE);
        tca = new MyTeamAdapter(context, type == 0 ? false : true);
        listView.setAdapter(tca);
        swipeLayout.setOnRefreshListener(this);

        listView.setStateListener(new IListView.SwipeLayoutState() {
            @Override
            public boolean isRefresh() {
                return swipeLayout.isRefreshing();
            }

            @Override
            public boolean isLastPage() {
                return total == currentPage;
            }

            @Override
            public void requestNextPage() {
//                requestTask(++currentPage);
            }
        });


        if (isNetvaiable()) {
            swipeLayout.post(new Thread(new Runnable() {

                @Override
                public void run() {
                    swipeLayout.setRefreshing(true);
                    onRefresh();
                }
            }));
        }
    }

    @OnItemClick(R.id.listView)
    void itemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putSerializable(Constants.ITEM, tca.getItem(position));
        IntentUtils.startActivity(context, TeamDetailActivity.class, bundle);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
//        //（1）将事件发布者发布的数据作为文本修改内容
//        msgFragment.setText(event.data);
        //（2）将事件发布者发布的数据作为方法执行的区分
        switch (event.getType()) {
            case EventBusEntity.Type.TEAM_EXIT:
                tca.replace(event.getPosition(), (TeamUser) event.getItem());
                break;
            case EventBusEntity.Type.REFRENCE_TEAM:
                swipeLayout.post(new Thread(new Runnable() {

                    @Override
                    public void run() {
                        swipeLayout.setRefreshing(true);
                        onRefresh();
                    }
                }));
                break;
        }
    }

    @Override
    public void start(int type) {

    }

    @Override
    public void success(int type, String json) {
        swipeLayout.setRefreshing(false);
        switch (type) {
            case TeamAPI.TEAM_INDEX_MARK:
                BaseModel base = JSONObject.parseObject(json, BaseModel.class);
                if (base.result.equals(Constants.SUCESS)) {
                    JSONObject object = JSONObject.parseObject(base.data);
                    currentPage = object.getInteger(Constants.CURRENT);
                    if (currentPage == 1) {
                        tca.clear();
                    }
                    listView.loadMoreFinish();
                    if (total == currentPage) {
                        listView.removeFooterView();
                    }
                    total = object.getInteger(Constants.TOTAL);

                    List<TeamUser> teamIndex = JSONObject.parseArray(JSONObject.parseObject(base.data).getString("list"),
                            TeamUser.class);
                    if (teamIndex != null && !teamIndex.isEmpty()) {
                        tca.addAllAfter(teamIndex);
                    } else {
                        T.showShort(getActivity(), base.msg);
                    }
                }

                break;
        }
    }

    @Override
    public void failed(String error) {
        swipeLayout.setRefreshing(false);
        T.showShort(getActivity(), error);
    }

    @Override
    public void finish(int type) {

    }

    @Override
    public void onRefresh() {
        //if (type == 1) //参与的团队
        TeamAPI.teamIndex(type + "", MyTeamFragment.this, null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
